package top.kaoshanji.p2ch17a;

import java.io.IOException;
import java.nio.file.*;
import java.util.concurrent.Executors;

/**
 * 代码清单-p2ch17a-540页a：监听整个目录树
 * 没有执行
 * author kaoshanji
 * ^_^
 * create time 2025/3/11 17:07
 */
public class TreeWatcher {

    @SuppressWarnings("resource")
    public static void main(String[] args) throws IOException {

        Files.walk(Paths.get("test"))
                .filter(Files::isDirectory)
                .forEach(TreeWatcher::watchDir);

        PathWatcher.delTxtFiles();
    }

    static void watchDir(Path dir) {

        try {
            WatchService watchService = FileSystems.getDefault().newWatchService();
            dir.register(watchService, StandardWatchEventKinds.ENTRY_DELETE);

            Executors.newSingleThreadExecutor().submit(() -> {
               try {
                   WatchKey key = watchService.take();
                   for (WatchEvent event: key.pollEvents()) {
                       System.out.println(
                               "evt.context(): " + event.context() +
                                       "\nevt.count(): " + event.count() +
                                       "\nevt.kind(): " + event.kind());
                       System.exit(0);
                   }
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

}